#include "myStdio.h"
FILE_* fopen_(const char* file_name, const char* mode)
{
    int flags = 0;
    if(strcmp("r", mode) == 0)
    {
        flags |= O_RDONLY;
    }
    else if(strcmp("w", mode) == 0)
    {
        flags |= O_WRONLY | O_CREAT | O_TRUNC;
    }
    else if(strcmp("a", mode) == 0)
    {
        flags |= O_WRONLY | O_CREAT | O_APPEND;
    }
    else 
    {
        //do other
    }
    int fd = 0;
    if(flags & O_RDONLY) fd = open(file_name, flags);
    else fd = open(file_name, flags, 0666);
    if(fd < 0)
    {
        const char* err = strerror(errno);
        write(2, err, strlen(err)); 
        return NULL;
    }
    FILE_* fp = (FILE_*)malloc(sizeof(FILE_));
    fp->flag = SYNC_LINE;
    fp->fileno = fd;
    memset(fp->buffer, 0, SIZE);
    fp->size = 0;
    fp->capacity = SIZE;
    return fp;
}


void fwrite_(const void* ptr, int num, FILE_* stream)
{
    //写入缓冲区
    memcpy(stream->buffer + stream->size, ptr, num);
    stream->size += num; //不考虑缓冲区满的情况
    //判断刷新策略
    //1.立即刷新
    if(stream->flag & SYNC_NOW)
    {
        write(stream->fileno, stream->buffer, stream->size);
        stream->size = 0;
    }
    //2.行刷新
    else if(stream->flag & SYNC_LINE)
    {
        if('\n' == stream->buffer[stream->size - 1]) //只考虑最后为\n的情况
        {
            write(stream->fileno, stream->buffer, stream->size);
            stream->size = 0;
        }
    }
    else if(stream->flag & SYNC_FULL)
    {
        if(stream->size == stream->capacity)
        {
            write(stream->fileno, stream->buffer, stream->size);
            stream->size = 0;
        }
    }
}
void fflush_(FILE_* stream)
{
    if(stream->size > 0)
    {
        write(stream->fileno, stream->buffer, stream->size);
    }
    //强制操作系统进行外设刷新
    fsync(stream->fileno);
    stream->size = 0;
    
}
void fclose_(FILE_* stream)
{
    fflush_(stream);
    close(stream->fileno);
}
